<template>
  <div>
    <Header
      @child-register="registerRe"
      @child-login="loginRe"/>
    <br>
    <!-- <p style="text-align:center;color:#606266">欢迎加入07ge</p> -->
    <p style="text-align:center;color:#606266">修改密码</p>
    <el-row type="flex" class="row-bg" justify="center">
    <el-col :xs="24" :sm="12" :md="10" :lg="8" :xl="6">
    <el-form id="ruleForm2" :model="ruleForm2" status-icon :rules="rules2" ref="ruleForm2" label-width="" class="demo-ruleForm">
      <!-- <el-form-item label="昵称" prop="name">
        <el-input name="name" v-model="ruleForm2.name" placeholder="请输入昵称" />
      </el-form-item> -->
      <el-form-item label="注册时的邮箱" prop="email">
          <el-input v-model="ruleForm2.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button v-if="canClick" plain type="primary" @click="sendMsg">获取邮件验证码</el-button>
        <el-button v-else type="info" plain disabled>{{ totalTime }}秒后重新获取验证码</el-button>
      </el-form-item>
      <el-form-item label="验证码 (请登录邮箱查看邮件)" prop="code" v-if="showNext">
          <el-input v-model="ruleForm2.code" maxlength="4" placeholder="请输入邮箱中收到的验证码"/>
      </el-form-item>
      <el-form-item label="新密码" prop="pass" v-if="showNext">
        <el-input type="password" v-model="ruleForm2.pass" autocomplete="off" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="checkPass" v-if="showNext">
        <el-input type="password" v-model="ruleForm2.checkPass" autocomplete="off" placeholder="请再次输入密码"></el-input>
      </el-form-item>
      <!-- <el-form-item label="验证码" prop="age">
        <el-input v-model.number="ruleForm2.age"></el-input>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" @click="registercg('ruleForm2')" v-if="showNext">提交修改密码</el-button>
        <el-button @click="resetForm('ruleForm2')" v-if="showNext">重置</el-button>
      </el-form-item>
    </el-form>
    <p style="text-align:center;color:#909399">请输入您注册时用的邮箱,收取验证码</p>
    </el-col>
    </el-row>
    <Footer/>
  </div>
</template>

<script>
import config from '@/config/config.js'
import 'element-ui/lib/theme-chalk/display.css';
import Header from '~/components/Header.vue'
import Footer from '~/components/Footer.vue'
import CryptoJS from 'crypto-js'

  export default {
    components: {
        Header, Footer
    },
    data() {
      var checkEmail = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('邮箱不能为空'));
        }
        setTimeout(() => {
          // let myreg = new RegExp("^(?=.*[@])+(?=.*[.])")
          let myreg = new RegExp("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$")

          if (!myreg.test(value)) {
            return callback(new Error('邮箱格式不对'));            
          } else {
            // return callback(new Error('OK'));  
            callback();          
          }
        }, 500);
      };
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else if (value.length < 8) {
          callback(new Error('密码至少有8位'));
        } else {
          if (this.ruleForm2.checkPass !== '') {
            this.$refs.ruleForm2.validateField('checkPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value.length < 8) {
          callback(new Error('密码至少有8位'));
        } else if (value !== this.ruleForm2.pass) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        totalTime: 60,
        showNext: false,
        canClick: true,
        domain: '',
        ruleForm2: {
          name: '',
          code: '',
          pass: '',
          checkPass: '',
          email: ''
        },
        rules2: {
          name: [
            {required: true, type: 'string', message: '请输入昵称', trigger: 'blur'}
          ],
          code: [
            {required: true, type: 'string', message: '请输入验证码', trigger: 'blur'}
          ],
          pass: [
            {required: true, validator: validatePass, trigger: 'blur' }
          ],
          checkPass: [
            {required: true, validator: validatePass2, trigger: 'blur' }
          ],
          email: [
            {required: true, validator: checkEmail, trigger: 'blur' }
          ]
        }
      };
    },
    mounted() {
      this.domain = config.getDomain()
    },
    methods: {
      // 跳转
      registerRe() {
        window.location.href='/register'
      },
      loginRe() {
        window.location.href='/login'
      },
      // 发送验证码
      sendMsg() {
        let namePass = this.ruleForm2.name
        let emailPass = this.ruleForm2.email 
        let myreg = new RegExp("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$")
        if (!myreg.test(emailPass)) return
        if (!this.canClick) return
        this.showNext = true
        this.canClick = false

        let clock = window.setInterval(() => {
          this.totalTime--
          if (this.totalTime < 0) {
          window.clearInterval(clock)
          this.totalTime = 60
          this.canClick = true  //这里重新开启
          }
        }, 1000)

        if (emailPass) {
          this.$axios.post('/users/verifycg', {
            // username: encodeURIComponent(namePass),
            email: emailPass
          }, {
            headers: {
              'Content-Type': 'application/json'
            }
          })
          .then(({
            status,
            data
          }) => {
            if (status === 200 && data && data.code === 0) {
              let count = 60;
              self.statusMsg = `验证码已发送,剩余${count--}秒`
              self.timerid = setInterval(function () {
                self.statusMsg = `验证码已发送,剩余${count--}秒`
                if (count === 0) {
                  clearInterval(self.timerid)
                }
              }, 1000)
            } else {
              self.statusMsg = data.msg
            }
          })
        }
      },
      // 修改密码
      registercg(formName) {
        let password = this.ruleForm2.pass
        let checkPass = this.ruleForm2.checkPass
        let email = this.ruleForm2.email
        let code = this.ruleForm2.code
        if (!code || !email || !password || !checkPass || password !== checkPass) {
          this.$message.error('请仔细检查必填项');
          return
        }
        if (password.length < 8) {
          this.$message.error('密码至少有8位');
          return
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$axios.post('/users/changepw', {
              // username: window.encodeURIComponent(self.ruleForm.name),
              password: CryptoJS.MD5(this.ruleForm2.pass).toString(),
              email: this.ruleForm2.email,
              code: this.ruleForm2.code
            }).then(({
              status,
              data
            }) => {
              if (status === 200) {
                if (data && data.code === 0) {
                  this.$message.success('修改密码成功3秒后进入登录页面');
                  setTimeout(()=>{
                    location.href = '/login'
                  }, 3300)
                } else {
                  this.error = data.msg
                  this.$message.error(data.msg);
                }
              } else {
                this.error = `服务器出错，错误码:${status}`
              }
              setTimeout(function () {
                this.error = ''
              }, 1500)
            })
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
  }
</script>

<style lang="scss">
.demo-ruleForm {
  text-align: center;
  padding-right: 5rem;
  padding-left: 5rem;
  margin: 3rem 0;
}
.hy {
  position: fixed;
  margin-top: 10rem;
  margin-left: 40rem;
  font-size: 20px;
  // text-align:right;
  // width: 100%;
  color:#F56C6C;
}
.row-bg {
  margin-bottom: 10rem;
}
</style>

